<!DOCTYPE html>
<html lang="zh">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" content="ie=edge"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>分类管理</title>
<#include "../common/easyui-html5.ftl"/>
</head>
<body class="easyui-layout">
	 <div data-options="region:'center'">
		<table id="dg"></table>
	</div>
	<!-- 工具条  -->
	<div id="tb" style="padding:5px;height:auto">
		<div style="margin-bottom:5px">
			<table width="100%">
			<tr width="100%">
				<td width="50%">
                    类别名称: <input class="easyui-textbox" style="line-height:12px; width:200px" id="role_Name"/>
					<!--
					状态:<select class="easyui-combobox" data-options="editable:false,panelHeight:'auto'" style="width:100px" id="role_status">
						<option value="0">不限</option>
						<option value="1">有效</option>
						<option value="2">待审核</option>
						<option value="3">锁定</option>
					</select> -->
					<a href="#"  class="easyui-linkbutton" iconCls="icon-search" onclick="searchFn()">查询</a>
				</td>
				<td align="right" width="50%">
					<a id="addBtn" href="#" class="easyui-linkbutton" iconCls="add_btn" plain="true" onclick="addFn()">增加</a>
				</td>
			</tr>
		</table>
		</div>
	</div>
	<!-- 弹出窗口  -->
	<div id="w" class="easyui-window"
		data-options="modal:true,closed:true,iconCls:'icon-save',
		collapsible:false,minimizable:false,maximizable:false,resizable:false"
			style="width:500px;height:420px;padding:10px;">
			<div class="easyui-layout" data-options="fit:true">

					<div data-options="region:'center',border:false" style="padding:10px;">
                        <form id="form1" method="post">
                        <table>
                            <tr style="display: none;">
                                <td>id:</td>
                                <td><input  type="text" id="form_id" name="id"></input>
                                    <input  type="hidden" id="ajax" name="ajax" value="true"></input>
								</td>
                            </tr>
                            <tr  >
                                <td>分类名称</td>
                                <td><input  type="text" id="catName" name="catName" class="easyui-textbox" data-options="" style="width:300px"></input></td>
                            </tr>
                            <tr  >
                                <td>上级分类</td>
                                <td><input  type="text" id="parentId" name="parentId"
                                            class="easyui-combotree"
                                            data-options="editable:false,required:true"
											  style="width:300px"></input></td>
                            </tr>
                            <tr  >
                                <td>数量单位</td>
                                <td><input  type="text" id="measureUnit" name="measureUnit" class="easyui-textbox" data-options="" style="width:300px"></input></td>
                            </tr>
                            <tr  >
                                <td>排序</td>
                                <td><input  type="text" id="sortOrder" name="sortOrder" class="easyui-numberspinner" data-options="editable:true,value:100,max:999" style="width:300px"></input></td>
                            </tr>
                            <tr  >
                                <td>是否显示</td>
                                <td>
                                    <select id="show" name="show" class="easyui-combobox" data-options="editable:false,panelHeight:true"   style="width:300px;">
                                        <option value="true">显示</option>
                                        <option value="false">不显示</option>
                                    </select>
                                </td>
                            </tr>
                            <tr  >
                                <td>是否显示在导航栏</td>
                                <td>
                                    <select id="showInNav" name="showInNav" class="easyui-combobox" data-options="editable:false,panelHeight:true"   style="width:300px;">
                                        <option value="true">显示</option>
                                        <option value="false">不显示</option>
                                    </select>
                                </td>
                            </tr>
                            <tr  >
                                <td>描述</td>
                                <td><input  type="text" id="catDesc" name="catDesc" class="easyui-textbox" data-options="multiline:true,height:50" style="width:300px"></input></td>
                            </tr>

                        </table>
                        </form>
					</div>
					<div data-options="region:'south',border:false" style="text-align:right;padding:5px 0 0;">
						<a class="easyui-linkbutton" data-options="iconCls:'icon-ok'" href="javascript:void(0)" onclick="javascript:submitForm()">保存</a>
						<a class="easyui-linkbutton" data-options="iconCls:'icon-cancel'" href="javascript:void(0)" onclick="javascript:closeWinFn()">取消</a>
					</div>

			</div>
	</div>
<script type="text/javascript">
var doPage =  authIds.indexOf(",admin_category_dopage,")>=0?true:false;
var doAddBtn =   authIds.indexOf(",admin_category_doadd,")>=0?true:false;
var doupdateBtn =  authIds.indexOf(",admin_category_doupdate,")>=0?true:false;
var dodelBtn =  authIds.indexOf(",admin_category_dodel,")>=0?true:false;
var saveType="add";
$(function(){
			if(!doAddBtn){
				$("#addBtn").hide();
			}
			$('#dg').treegrid({
			 	border:false,
				rownumbers:true,
				checkOnSelect:true,
				fitColumns:true,
				singleSelect:true,
				fit:true,
                idField:'id',
                treeField:'catName',
				method:'get',
			  	url:'${rc.contextPath}/admin/category/dopage?d='+new Date().getTime(),
			  	queryParams:{ },
			  	onBeforeLoad:function(param){
                    if(!doPage){
                        $.messager.alert('系统提示','您没有权限访问!','info');
                        return;
                    }
					//param['pageno'] =  param['page']-1;
					//param['pagesize']  = param['rows'];
			  		return true ;
			  	},
			  	onDblClickRow:function(rowIndex, rowData){
			  			//updateRowIndex = rowIndex;
						//getRoleInfoById(rowData['roleId']);
			  	},
			  	onLoadError:function(){
			  	},

				columns:[[
					{field:'id',title:'id' ,width:100},
					{field:'catName',title:'分类名称' ,width:100},
                    {field:'catDesc',title:'描述' ,width:100},
                    {field:'sortOrder',title:'顺序' ,width:100},
                    {field:'measureUnit',title:'单位' ,width:100},
                    {field:'showInNav',title:'导航栏显示' ,width:100,formatter:function(value,row,index){
                        if(value){
                            return "显示";
                        }else  {
                            return "不显示";
                        }
                    }},
                    {field:'show',title:'是否显示' ,width:100,formatter:function(value,row,index){
                        if(value){
                            return "显示";
                        }else  {
                            return "不显示";
                        }
                    }},
					{field:'states',title:'状态',width:100,formatter:function(value,row,index){
						if(value == 'NORMAL'){
							return "有效";
						}else  if(value == 'DEL'){
							return "删除";
						}
					}},
					{field:'opt',title:'操作' ,width:100,formatter:optFormat}
				]],
				toolbar: '#tb',
				loadFilter:function(data){
				   if(data.statusCode == normalStatusCode){
                        	var obj = {};
                            obj.total =  data.entity.totalRows;
                            obj.rows = $.isArray(data.entity.pageData)?data.entity.pageData:[];
					        var rArray = [];
					        for(var i=0;i<obj.rows.length;i++){
								var item = obj.rows[i];
                               item._parentId= item.parentId;
								if(item._parentId == '0'){
                                    delete item._parentId;
								}
                                rArray.push(item)
							}

                       		obj.rows = rArray;

					   		window.treeData = obj.rows;

                            return obj;
				   }else {
				            var obj = {};
                           obj.total = 0;
                            obj.rows = [];
                            window.treeData = [];
                            return obj;
				   }

				}
			});

		});

		function searchFn(){
			if(!doPage){
				 $.messager.alert('系统提示','您没有权限访问!','info');
				return;
			}
			var role_Name = $("#role_Name").val();
			//var role_status = $('#role_status').combobox('getValue');
			$('#dg').datagrid('load',{
					//status:role_status,
					name:role_Name,
					d:new Date().getTime()
			});

		}
		var updateRowIndex = -1;
function addFn(){
	 saveType = "add";
	$('#form1').form('reset');
	 $('#w').window('open').panel('setTitle',"增加分类");

	//for(var i=0;i<data.length;i++){ if(data[i]['button'] == false){ menus.push(data[i]); } }
	var tree2Data = makeTreeData(window.treeData,false);
	var  newTree2Data = [{
		"id":0,
		"text":"顶级分类",
		"children":tree2Data
	}];

    $('#parentId').combotree("readonly",false);
	$('#parentId').combotree('loadData',newTree2Data);
	$('#parentId').combotree('setValue',0);
}
 function delFn(id){

			$.messager.confirm('系统提示', '您确定要删除该条记录吗?', function(r){
			if (r){
					var url = "${rc.contextPath}/admin/category/dodel?id="+id;
		  	 		$.ajax({
			  	  	  type:'post',
					  url: url,
					  context: document.body,
					  data:{
                        	d:new Date().getTime()
					  },
					  success:function(data){

					  	if(data.statusCode == normalStatusCode){
                            $('#dg').treegrid('reload');
					  		$.messager.alert('系统提示','删除成功!','info');

					  	}else{
					  		$.messager.alert('系统提示','删除失败，请刷新后重试!','error');
					  	}
					  },
					  error:function(xhr,textStatus,errorThrown){
					  	var responseText = xhr.responseText;
					  	$.messager.alert('系统提示','删除失败，请刷新后重试!','error');

					  }
				});

				}
			});
		}
		function optFormat (value,row,index){
			var btns = [];
			if(doupdateBtn){
				btns.push('<a class="easyui-linkbutton l-btn l-btn-plain" onclick="updateFn(\''+row['id']+'\')" href="#" plain="true" iconCls="update_btn"><span class="l-btn-left"><span class="l-btn-text update_btn l-btn-icon-left">修改</span></span></a>');
			}
			if(dodelBtn){
				btns.push('<a class="easyui-linkbutton l-btn l-btn-plain" onclick="delFn(\''+row['id']+'\')" href="#" plain="true" iconCls="del_btn"><span class="l-btn-left"><span class="l-btn-text del_btn l-btn-icon-left">删除</span></span></a>');
			}
			return btns.join("&nbsp;");
		}
		function updateFn(id){
            saveType = 'update';
			var row = $("#dg").treegrid("find",id);
            $('#form1').form('reset');

            var tree2Data = makeTreeData(window.treeData,false);
            var  newTree2Data = [{
                "id":0,
                "text":"顶级分类",
                "children":tree2Data
            }];
            $('#parentId').combotree('loadData',newTree2Data);
            $('#parentId').combotree("readonly",true);
            $('#form1').form('load',row);


            var show = row['show'];
            if(show){
                $('#show').combo('setText', "显示");
            }else {
                $('#show').combo('setText', "不显示");
            }

            var showInNav = row['showInNav'];
            if(showInNav){
                $('#showInNav').combo('setText', "显示");
            }else {
                $('#showInNav').combo('setText', "不显示");
            }

            $('#w').window('open').panel('setTitle',"修改分类");

		}

		function submitForm(){
			 var isValidate = $('#form1').form('validate');
			 if(!isValidate){
			 	$.messager.alert('系统提示','请确保填写正确!','warning');
			 	return;
			 }

			var catName = $.trim($("#catName").val());

			if(catName.length ==0 ){
				$.messager.alert('系统提示','分类名称不能为空!','warning');
				return;
			}
			var url = "${rc.contextPath}/admin/category/doadd";

			if(saveType == 'add'){

			}else if(saveType == 'update'){
                url = "${rc.contextPath}/admin/category/doupdate";
			}
            $('#form1').form('submit', {
                url:url,

                queryParams:{
					ajax:true
				},
                onSubmit: function(param){
                    //param.p1 = 'value1';
                    //param.p2 = 'value2';

                    var sortOrder = $('#sortOrder').numberbox('getValue');
                    if(sortOrder*1 > 1000){
                        $.messager.alert('系统提示','排序不能大于1000','warning');
                        return false;
                    }
                    jQuery.showMask($("#w")[0],"正在保存中 ....");
                    return true;

                },
                success: function(data){
                    jQuery.hideMask($("#w")[0]);
                    data = eval("("+data+")");
                    if(data.statusCode == normalStatusCode){
                        $('#dg').treegrid('reload');
                        $.messager.alert('系统提示','保存成功!','info',closeWinFn);
                    }else{
                        $.messager.alert('系统提示','保存失败!','info');
                    }
                    //  var data = eval('(' + data + ')');  // change the JSON string to javascript object
                }
            });
		}

		function closeWinFn(){
			$('#w').window('close');
		}

function makeTreeData(menus,usecheck){

	if(menus.length==0)return menus;
 	 var mapdata = {};
	  //第一次组织树节点内容
	  for(var i=0;i<menus.length;i++)
	  {
	      var node = menus[i];
	      var menuname = node['catName'];
	      var pid = node['_parentId'];
	      var aid = node['id'] ;

			var obj = {
	    		  id:aid,
	    		  text:menuname,
	    		 // "iconCls":isbutton!=1?"tree-file":"icon-add",
	    		  attributes:{
	    		  	pid:pid
	    		  }

	    		};
	      mapdata["id_"+aid]= obj;
	     if(usecheck)
		 {
		 	mapdata["id_"+aid]['checked']=false;
		 }

	  }
  var ret = [];
  for(var key in mapdata)
  {
      var node = mapdata[key];
      var pid = mapdata[key]['attributes']['pid'];
      if(mapdata["id_"+pid])
      {
          if(typeof mapdata["id_"+pid]['children'] == 'undefined')
          {
              mapdata["id_"+pid]['children'] = [];
          }
          mapdata["id_"+pid]['children'].push(mapdata[key]);
      }else
      {
          ret.push(mapdata[key]);
      }
  }
  return ret;
}

	</script>
</body>
</html>